<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use buwang\facade\WechatPay;
use app\common\model\member\Wallet;
use app\common\model\member\WalletRecharge;
use buwang\base\MemberBaseController;
use buwang\util\alipay\AliPay;
use Exception;

class Notify extends MemberBaseController
{
    /**
     * 租户后台微信扫码充值余额 支付回调
     * @return \think\Response
     */
    public function index()
    {
        try {
            $response = WechatPay::doPay()->handlePaidNotify(function ($message, $fail) {
                $rel = WalletRecharge::where(['order_sn' => $message['out_trade_no'], 'state' => 0])->find();
                if (empty($rel)) return true;
                if ($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'SUCCESS') {
                    $ispay = WechatPay::doPay()->order->queryByOutTradeNumber($rel->order_sn);
                    if ($ispay['return_code'] === 'SUCCESS' && $ispay['result_code'] === 'SUCCESS' && $ispay['trade_state'] === 'SUCCESS'
                        && $ispay['total_fee'] == $rel->money * 100) {
                        $rel->state = 1;
                        $rel->update_time = time();
                        $rel->transaction_id = $ispay['transaction_id'];;
                        $rel->save();

                        Wallet::changeMoney($rel->member_id, 'recharge', $ispay['total_fee'] / 100, '微信充值');
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 支付宝支付成功回调 支付回调
     */
    public function ali_notify_page()
    {
        $params = $this->request->param();
        $result = $this->notifyHandle($params);
        if (true === $result) {
            echo 'success';
        } else {
            echo 'fail';
        }
    }

    /**
     * 支付回调
     */
    public function notifyHandle($data)
    {
        try {
            $order_sn = $data['out_trade_no']??'';
            file_put_contents(root_path().'runtime/ali_notify.txt', date('Y-m-d H:i:s', time()) . '-' . "支付宝回调处理start{$order_sn}：data=".json_encode($data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
            $aliPay = new AliPay();
            $verify = $aliPay->alipayVerifyNotify($data);
            if (false === $verify) {
                file_put_contents(root_path().'runtime/ali_notify.txt', date('Y-m-d H:i:s', time()) . '-' . "支付宝回调处理{$order_sn}：验签失败：data=".json_encode($data,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                return false;
            }
            //TRADE_SUCCESS交易支付成功。TRADE_FINISHED交易结束，不可退款。
            if (!in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                file_put_contents(root_path().'runtime/ali_notify.txt', date('Y-m-d H:i:s', time()) . '-' . "支付宝回调处理{$order_sn}：没有支付完成".PHP_EOL,FILE_APPEND);
                return false;
            }

            //验证订单是否已支付
            $passback_params = $data['passback_params']??'';
            //租户余额充值
            if ($passback_params == 'recharge'){
                $rel = WalletRecharge::where(['order_sn' => $order_sn, 'state' => 0])->find();
                if (!$rel){
                    file_put_contents(root_path().'runtime/ali_notify.txt', date('Y-m-d H:i:s', time()) . '-' . "支付宝回调处理{$order_sn}：订单不存在".PHP_EOL,FILE_APPEND);
                    return false;
                }
                $rel->state = 1;
                $rel->update_time = time();
                $rel->transaction_id = $data['trade_no']??'';
                $rel->save();

                //修改用户余额
                Wallet::changeMoney($rel->member_id, 'recharge', $data['total_amount'], '支付宝充值');
            }
            return true;
        } catch (\Throwable $e) {
            file_put_contents(root_path().'runtime/ali_notify.txt', date('Y-m-d H:i:s', time()) . '-' . "支付宝回调处理异常=".$e->getFile().$e->getLine().$e->getMessage().PHP_EOL,FILE_APPEND);
            return false;
        }
    }
}